import style from './index.module.less'
import { Form, TextArea, Button, Toast, Dialog, Input, NoticeBar } from 'antd-mobile'
import PageComponent from '@components/pageComponent'
import { getCaseDetailRequest, updateData } from './ajax'
import { awaitWrap, getSearch, getUrlPre, setSearch } from '@src/assets/js/tool'
import { useEffect, useState } from 'react'
import { refreshCaseDetailVersion, refreshCaseEditVersion } from '@src/redux/reducers/cases'
import { pop } from '@src/redux/reducers/pages'
import { useAppDispatch } from '@src/redux/hook'
import FilePicker from '@components/filePicker'
import { requestFiles } from '@src/assets/js/request'
import { setProgress, setProgressVisible } from '@src/redux/reducers/common'
import { AudioOutline } from 'antd-mobile-icons'
import { useHistory } from 'react-router-dom'

const { Item, useForm } = Form

async function initData (caseid, id, formRef, setData) {
  Toast.show({ content: '加载中', icon: 'loading', duration: 0 })
  const [e, d] = await awaitWrap(getCaseDetailRequest(caseid))
  if (e === null) {
    Toast.clear()
    if (d) {
      setData(d)
      const o = d.evidence.find(li => li.id === id) || {}
      const s = getSearch()
      if (s.result) {
        o.proof = decodeURIComponent(s.result)
      }
      formRef.setFieldsValue(o)
    }
  }
}

async function submitHandle (caseid, d, caseDetail, dispatch) {
  if (d.file && d.file.length > 0) {
    dispatch(setProgressVisible(true))
    const [e, r] = await awaitWrap(requestFiles(d.file, v => { dispatch(setProgress(v)) }))
    dispatch(setProgressVisible(false))
    if (e !== null) {
      return undefined
    }
    if (e === null && r !== null) {
      d.fileid = r.map(li => li.id).join(',')
    }
  }
  delete d.file
  Toast.show({ content: '提交中', icon: 'loading', duration: 0 })
  const [e] = await awaitWrap(updateData(caseid, d))
  if (e === null) {
    Toast.clear()
    Toast.show({ content: '提交成功', icon: 'success' })
    dispatch(refreshCaseEditVersion())
    dispatch(refreshCaseDetailVersion())
    dispatch(pop())
  }
}

function Main ({ meta: { caseid = '', id = '' } = { case: '', id: '' } }) {
  const [formRef] = useForm()
  const h = useHistory()
  const dispatch = useAppDispatch()
  const [data, setData] = useState(null)
  useEffect(() => {
    if (formRef && caseid) {
      initData(caseid, id, formRef, setData)
    }
  }, [caseid, id, formRef])
  return (
    <PageComponent title={id ? '编辑证据材料' : '添加证据材料'} onBack={() => { setSearch(h, { result: '' }); dispatch(pop()) }}>
      {/* <div className={style.notice}>
        <span></span>
      </div> */}
      <NoticeBar color='alert' icon={false} wrap content={
        <div>
          证据材料一般情况包括：<br />1. 证明权利义务关系材料：如合同、交易订单等；<br />2. 证明履约材料：如支付流水、交货确认定等；<br />3. 证明相对方违约材料：如逾期通知，欠费单等。
        </div>
      } />
      <Form layout='horizontal' form={formRef} onFinish={d => {
        Dialog.confirm({
          title: '您确定要提交吗？',
          onConfirm: () => {
            setSearch(h, { result: '' })
            submitHandle(caseid, d, data, dispatch)
          }
        })
      }}>
        <Item name='id' noStyle><span /></Item>
        <Item label='证据名称' name='name' rules={[{ required: true, message: '证据名称不能为空' }]}>
          <Input placeholder='请输入' clearable />
        </Item>
        <div className={style.desc}>
          <div className={style['audio-btn']} onClick={() => {
            const city = getUrlPre()
            // eslint-disable-next-line no-undef
            if (typeof wx !== 'undefined' && wx.miniProgram) {
                // eslint-disable-next-line no-undef
                wx.miniProgram.navigateTo({
                    url: `/pages/voiceToText/simple-voice?fromH5=true&city=${city}`
                });
            }
          }}>
            <AudioOutline />
          </div>
          <Item label='证明内容' name='proof' rules={[{ required: true, message: '证明内容不能为空' }]}>
            <TextArea placeholder='请输入' clearable autoSize={{ minRows: 3 }} />
          </Item>
        </div>
        <Item name='file' label='附件' rules={[{ required: true, message: '附件不能为空' }]}>
          <FilePicker />
        </Item>
        <Item>
          <div className={style.btns}>
            <Button type='submit' color='primary' block>提交</Button>
          </div>
        </Item>
      </Form>
    </PageComponent>
  )
}

export default Main
